package com.tom.architect.day07.diy;

public class Looper {
	// sThreadLocal.get() will return null unless you've called prepare().
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
	public static void prepare() {
        sThreadLocal.set(new Looper());
	}
	MessageQueue mQueue;
	
	public Looper() {
		// 初始化
		mQueue = new MessageQueue();
	}

	public static void loop() {
		Looper looper = myLooper();
		for(;;) { // 死循环：不断从mQueue中拿msg。
			MessageQueue queue = looper.mQueue; // 消息队列
			Message message = queue.next(); // 队列中取出消息
			if(message == null){
				return;
			}
			message.target.handleMessage(message);
		}
	}
	static Looper myLooper() {
		return sThreadLocal.get(); // 拿到唯一的looper对象
	}
}
